package com.sczmgk.hotline_pzh.ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;

import com.google.gson.Gson;
import com.sczmgk.hotline_pzh.MyApp;
import com.sczmgk.hotline_pzh.R;
import com.sczmgk.hotline_pzh.base.RefreshAndLoadMoreBaseActivity;
import com.sczmgk.hotline_pzh.callback.OnRefreshListener;
import com.sczmgk.hotline_pzh.callback.SimplePaserJsonCallback;
import com.sczmgk.hotline_pzh.constants.Constants;
import com.sczmgk.hotline_pzh.db.impl.ChatMsgDaoImpl;
import com.sczmgk.hotline_pzh.db.impl.NewMsgCountDaoImpl;
import com.sczmgk.hotline_pzh.db.impl.UserDaoImpl;
import com.sczmgk.hotline_pzh.entity.MessageCountBean;
import com.sczmgk.hotline_pzh.entity.User;
import com.sczmgk.hotline_pzh.httputils.MyHttp;
import com.sczmgk.hotline_pzh.hxim.ChatMessageComparator;
import com.sczmgk.hotline_pzh.hxim.ChatMsgBean;
import com.sczmgk.hotline_pzh.hxim.HxAccount;
import com.sczmgk.hotline_pzh.hxim.HxImUtils;
import com.sczmgk.hotline_pzh.jpush.UIObserver;
import com.sczmgk.hotline_pzh.sp.CacheUtils;
import com.sczmgk.hotline_pzh.utils.CommonUtils;
import com.sczmgk.hotline_pzh.utils.MyLog;
import com.sczmgk.hotline_pzh.utils.MyToast;
import com.sczmgk.hotline_pzh.utils.Tools;
import com.sczmgk.hotline_pzh.view.ChatMessageView;
import com.sczmgk.hotline_pzh.view.RefreshListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.sczmgk.hotline_pzh.MyApp.hxImUtils;


/**
 * Created by Administrator on 2016/12/1 0001.
 */
public class ChatActivity extends RefreshAndLoadMoreBaseActivity<ChatMsgBean> implements View.OnClickListener{

    private ImageButton mVoice;
    private String fromhxid;
    private  Button addMsg,deleteMsg;
    private Button mSendBtn;
    private EditText mContent;
    private final int UPDATE_STATUS = 1;
    private MyAdapter adapter;
    private Handler uploadMsgHandler;
    private User user;
    private List<ChatMsgBean> cacheMessages = new ArrayList<ChatMsgBean>();
    private ChatMessageComparator chatMessageComparator = new ChatMessageComparator();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intelligent_answer);
        initData();
        loadData(1,"",LOAD_NORMAL);
        initView();
        initTitle();
        setListener();
        intiHadnler();
        uploadMsgHandler.postDelayed(upladMsgRunnable,1000*10);

    }


    /**
     * 将正在发送的消息改成发送失败()
     */
    private Runnable upladMsgRunnable = new Runnable() {
        @Override
        public void run() {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    List<ChatMsgBean> all = ChatMsgDaoImpl.getIntance(ChatActivity.this).findAll();
                    if(all!=null && all.size()>0){
                        for(int i = 0;i<all.size();i++){
                            ChatMsgBean msgBean = all.get(i);
                            if(msgBean.getStatus() == ChatMsgBean.MSG_STATUS_SENDING){//数据库里存的消息为正在发送则设置成发送失败
                                msgBean.setStatus(ChatMsgBean.MSG_STATUS_SEND_FAIL);
                            }
                            //TODO
//                            MyApp.hxImUtils.updateMsg(all.get(i),0);
                        }
                        hxImUtils.updateMsgs(all,0);
                    }
                }
            }).start();

        }
    };
    private void intiHadnler() {
        uploadMsgHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
             }
        };
    }

    @Override
    public void setListener() {
        super.setListener();
        mSendBtn.setOnClickListener(this);
        //注册消息监听
        hxImUtils.setSendMesgCallback(sendMesgCallback);
        mVoice.setOnClickListener(this);
        addMsg.setOnClickListener(this);
        deleteMsg.setOnClickListener(this);
        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {

                int postion = mListView.getFirstVisiblePosition();
                MyLog.d(TAG,"");
            }
        });
    }




    private HxImUtils.SendMesgCallback sendMesgCallback = new HxImUtils.SendMesgCallback() {
        @Override
        public void onSendStatusChanged(ChatMsgBean message) {
            //1.找到list里的数据
            //2.更新状态
            updateMsgStatus(message);

        }
        @Override
        public void createMsgCallback(ChatMsgBean message) {
            String msgid1 = message.getMsgid();
            lists.add(message);
            refreshList(-1);
            MyLog.i(TAG,"界面增加一条新消息---------->  mymsgid: "+message.getChatid());
        }
    };

    private void updateMsgStatus(ChatMsgBean message) {
        String msgid1 = message.getChatid();
        for(int i = 0;i< lists.size();i++ ){
            ChatMsgBean msgBean = lists.get(i);
            String msgid = msgBean.getChatid();
            if(msgid.equals(msgid1)){
                MyLog.d(TAG,"更新发送消息的状态 -----> mymsgid: "+msgid);
                msgBean.setStatus(message.getStatus());
                Message msg = Message.obtain();
                msg.what = UPDATE_STATUS;
                msg.obj = msgBean;
                mHandler.sendMessage(msg);
            }
        }
    }

    private void initTitle() {

        setTitle(R.string.chat_title);
        setNextRightBtnVisibility(View.VISIBLE);

        //设置拨打电话的图标
        setNextRightBtnBackground(R.drawable.call_phone);

        setNextRightBtnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //拨打电话
                CommonUtils.callPhone(ChatActivity.this , getResources().getString(R.string.customer_service_num_detail));
            }
        });
    }

    private void initView() {
        addMsg = (Button)findViewById(R.id.bt_add_msg);
        deleteMsg = (Button)findViewById(R.id.bt_delete_msg);
        mVoice = (ImageButton)findViewById(R.id.ib_voice_switch);
        mSendBtn = (Button) findViewById(R.id.bt_send_msg);
        mContent = (EditText) findViewById(R.id.et_send_text_content);
        mListView = (RefreshListView) findViewById(R.id.lv_chat_list);
        mListView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);//设置条目增加后自动显示最后一行
        adapter = new MyAdapter();
        mListView.setAdapter(adapter);
        mListView.setEnableLoadMore(false);
        mListView.setSelection(lists.size() - 1);//设置显示最后一行

        mListView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onPullDownRefresh() {
                int totalItemCount = mListView.getCount();
                //TODO 加载更多的操作

            }

            @Override
            public void onLoadingMore() {

            }
        });
    }

    private void initData() {
        int userid = CacheUtils.getIntData(ChatActivity.this,Constants.LOGIN_UID,0);
        user = UserDaoImpl.getIntance(ChatActivity.this).findByQuery(userid);

        //1.取得环信帐号
        //2.网络更新用户信息
        //3.登录

        if(Tools.isEmpty(user.easemobsaccount)){
            Map<String,Object> maps = new HashMap<>();
            maps.put("imei",MyApp.imei);
            maps.put("userid",userid);
            MyHttp.requestByCommon(Constants.BASE_URL + Constants.GET_HX_ACCOUNT_URL, maps, MyHttp.GET, ChatActivity.this, false, null, new SimplePaserJsonCallback() {
                @Override
                public void onVerifyIsNull() {

                }

                @Override
                public void onVerifySuccess(String dataRaw, boolean isCache) {
                    // 登录
                    Gson gson = new Gson();
                    HxAccount hxAccount = gson.fromJson(dataRaw, HxAccount.class);
                    //更新用户信息
                    updateUserInfo(hxAccount);

                }
            });
        }else{
            hxImUtils.login(user.easemobsaccount,user.easemobspassword);
            hxImUtils.initIm();
        }



    }

    private void updateUserInfo(final HxAccount hxAccount) {
        Map<String, Object> maps = new HashMap<>();
        maps.put("userid", user.userid);
        maps.put("headurl", user.headurl);
        maps.put("address", user.address);
        maps.put("sex", user.sex);
        maps.put("nickname", user.nickname);
        maps.put("phone", user.phone);
        maps.put("easemobsaccount", hxAccount.username);
        maps.put("easemobspassword", hxAccount.password);

        MyHttp.requestByCommon(Constants.BASE_URL + Constants.POST_UPDATE_USERINFO, maps, MyHttp.POST, ChatActivity.this, false, null, new SimplePaserJsonCallback() {
            @Override
            public void onVerifyIsNull() {

                //提交成功后将地址更新至数据库
                user.easemobsaccount = hxAccount.username;
                user.easemobspassword = hxAccount.password;
                UserDaoImpl.getIntance(ChatActivity.this).updata(user);
                //登录
                hxImUtils.login(user.easemobsaccount,user.easemobspassword);
                //
            }
            @Override
            public void onVerifySuccess(String dataRaw, boolean isCache) {
            }
        });
    }

    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        switch(msg.what){
            case REFRESH_LIST:
                final int position = (int) msg.obj;
                adapter.notifyDataSetChanged();

                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mListView.setSelection(position);
                    }
                },0);

                break;
            case UPDATE_STATUS:
//                ChatMsgBean msgBean = (ChatMsgBean) msg.obj;
//                ChatMessageView chatMessageView = (ChatMessageView)mListView.findViewWithTag(msgBean);//找到item
//                if(chatMessageView != null){
//                    chatMessageView.setMessage(msgBean);
//                    MyLog.d(TAG,"找到 message item    设置状态是:  "+msgBean.getStatus());
//                }
                adapter.notifyDataSetChanged();
                break;
        }

    }

    @Override
    public boolean getIsNeedLogin() {
        return true;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.bt_send_msg:
                String content = mContent.getText().toString().trim();
                if(Tools.isEmpty(content)){
                    MyToast.show(ChatActivity.this,getString(R.string.toast_intput_msg_content));
                    return;
                }
                hxImUtils.sendTextMsg(content);
                mContent.setText("");
//                mContent.clearFocus();
             break;
            case R.id.ib_voice_switch:

                break;
            case R.id.bt_add_msg:
                //测试存一条消息到数据库
                ChatMsgBean msgBean = ChatMsgBean.getTextMsg(1,"txt","bobo","msgbody",1,1,1221122212,"12121212212",0,"fk1",1,1,1);
                ChatMsgDaoImpl.getIntance(this).insert(msgBean);
                List<ChatMsgBean> all = ChatMsgDaoImpl.getIntance(this).findAll();
                MyLog.d(TAG,"add  cache msg size: "+all.size());
                break;
            case R.id.bt_delete_msg:
                ChatMsgDaoImpl.getIntance(this).deleteAll();
                List<ChatMsgBean> all1 = ChatMsgDaoImpl.getIntance(this).findAll();
                MyLog.d(TAG,"delete cache msg size: "+all1.size());
                break;
        }
    }


    private class MyAdapter extends BaseAdapter {

        public MyAdapter() {
            super();
        }

        @Override
        public int getCount() {
            return lists.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ChatMsgBean message = lists.get(position);
//            if (convertView == null) {
            convertView = View.inflate(ChatActivity.this, R.layout.chat_content_item, null);
//            }
            ChatMessageView chatMessageItem = (ChatMessageView) convertView;
            //打开,内容长按的处理
            chatMessageItem.setLongClickEnabled(true);
            message.setHeadUrl(user.imageLocalPath);
            chatMessageItem.setMessage(message);

            return convertView;
        }
    }


    @Override
    public Map<String, Object> getRequestData(int page, String keyword) {

        Map<String,Object> maps = new HashMap<>();
        maps.put("userid",user.userid);
        maps.put("page",page);
        maps.put("imei",MyApp.imei);
        return maps;
    }

    @Override
    public String getRquestUrl() {

        return Constants.BASE_URL + Constants.GET_CHAT_MSG_URL;
    }

    @Override
    public int getListType() {
        return LIST_TYPE_DOWN_LOAD_MORE;
    }
    /**
     * 发消息更新list
     */
    protected void refreshList(int position) {
        Message msg = Message.obtain();
        msg.what = REFRESH_LIST;
        msg.obj = position;
        mHandler.sendMessage(msg);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        hxImUtils.setChatIsForegound(false);
    }
    private void makeMsgAsReaded(){
        NewMsgCountDaoImpl.getIntance(ChatActivity.this).deleteAll();
        UIObserver.getInstance().hasNewMes(new MessageCountBean());
        //通知改变界面
    }

    @Override
    protected void onResume() {
        super.onResume();
        hxImUtils.setChatIsForegound(true);
        makeMsgAsReaded();
    }

    @Override
    protected void onStop() {
        List<ChatMsgBean> all = ChatMsgDaoImpl.getIntance(ChatActivity.this).findAll();
        hxImUtils.updateMsgs(all,0);

        super.onStop();
    }

}
